{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 随机抽样\n",
    "\n",
    "numpy.random 模块对 Python 内置的 random 进行了补充，增加了一些用于高效生成多种概率分布的样本值的函数，如正态分布、泊松分布等。\n",
    "\n",
    "\n",
    "\n",
    "- `numpy.random.seed(seed=None)` Seed the generator.\n",
    "\n",
    "`seed()`用于指定随机数生成时所用算法开始的整数值，如果使用相同的`seed()`值，则每次生成的随机数都相同，如果不设置这个值，则系统根据时间来自己选择这个值，此时每次生成的随机数因时间差异而不同。\n",
    "\n",
    "在对数据进行预处理时，经常加入新的操作或改变处理策略，此时如果伴随着随机操作，最好还是指定唯一的随机种子，避免由于随机的差异对结果产生影响。\n",
    "\n",
    "---\n",
    "\n",
    "## 离散型随机变量\n",
    "\n",
    "### 二项分布\n",
    "\n",
    "二项分布可以用于只有一次实验只有两种结果，各结果对应的概率相等的多次实验的概率问题。比如处理猜10次拳赢6次的概率等类似的问题。\n",
    "\n",
    "二项分布概率函数的代码表示：binom.pmf(k) = choose(n, k) p\\*\\*k (1-p)\\*\\*(n-k)\n",
    "\n",
    "二项分布概率函数的数学表示：\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131404914.png#pic_center)\n",
    "\n",
    "\n",
    "- `numpy.random.binomial(n, p, size=None)` Draw samples from a binomial distribution.\n",
    "\n",
    "表示对一个二项分布进行采样，`size`表示采样的次数，`n`表示做了`n`重伯努利试验，`p`表示成功的概率，函数的返回值表示`n`中成功的次数。\n",
    "\n",
    "【例】野外正在进行9（n=9）口石油勘探井的发掘工作，每一口井能够开发出油的概率是0.1（p=0.1）。请问，最终所有的勘探井都勘探失败的概率？\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy import stats\n",
    "\n",
    "np.random.seed(20200605)\n",
    "n = 9# 做某件事情的次数\n",
    "p = 0.1# 做某件事情成功的概率\n",
    "size = 50000\n",
    "x = np.random.binomial(n, p, size)\n",
    "'''或者使用binom.rvs\n",
    "#使用binom.rvs(n, p, size=1)函数模拟一个二项随机变量,可视化地表现概率\n",
    "y = stats.binom.rvs(n, p, size=size)#返回一个numpy.ndarray\n",
    "'''\n",
    "print(np.sum(x == 0) / size)  # 0.3897\n",
    "\n",
    "plt.hist(x)\n",
    "plt.xlabel('随机变量：成功次数')\n",
    "plt.ylabel('样本中出现的次数')\n",
    "plt.show()\n",
    "#它返回一个列表，列表中每个元素表示随机变量中对应值的概率\n",
    "s = stats.binom.pmf(range(10), n, p)\n",
    "print(np.around(s, 3))\n",
    "# [0.387 0.387 0.172 0.045 0.007 0.001 0.    0.    0.    0.   ]\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131434736.png?)\n",
    "\n",
    "\n",
    "【例】模拟投硬币，投2次，请问两次都为正面的概率？\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "from scipy import stats\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "np.random.seed(20200605)\n",
    "n = 2# 做某件事情的次数,这里是投两次硬币\n",
    "p = 0.5#做某件事情成功的概率，在这里即投硬币为正面的概率\n",
    "size = 50000\n",
    "x = np.random.binomial(n, p, size)\n",
    "'''或者使用binom.rvs\n",
    "#使用binom.rvs(n, p, size=1)函数模拟一个二项随机变量,可视化地表现概率\n",
    "y = stats.binom.rvs(n, p, size=size)#返回一个numpy.ndarray\n",
    "'''\n",
    "print(np.sum(x == 0) / size)  # 0.25154\n",
    "print(np.sum(x == 1) / size)  # 0.49874\n",
    "print(np.sum(x == 2) / size)  # 0.24972\n",
    "\n",
    "plt.hist(x)\n",
    "plt.xlabel('随机变量：硬币为正面次数')\n",
    "plt.ylabel('50000个样本中出现的次数')\n",
    "plt.show()\n",
    "#它返回一个列表，列表中每个元素表示随机变量中对应值的概率\n",
    "s = stats.binom.pmf(range(n + 1), n, p)\n",
    "print(np.around(s, 3))\n",
    "# [0.25 0.5  0.25]\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201123214715110.png)\n",
    "\n",
    "```\n",
    "#计算期望和方差\n",
    "'''\n",
    "期望：E(x) = np\n",
    "方差：Var(x) = np(1-p)\n",
    "利用stats.binom.stats(n, p, loc=0, moments='mv')计算期望和方差\n",
    "moments参数中:m为期望，v为方差\n",
    "'''\n",
    "```\n",
    "\n",
    "### 泊松分布\n",
    "\n",
    "泊松分布主要用于估计某个时间段某事件发生的概率。\n",
    "\n",
    "泊松概率函数的代码表示：poisson.pmf(k) = exp(-lam) lam\\*k / k!\n",
    "\n",
    "泊松概率函数的数学表示：\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131554335.png#pic_center)\n",
    "\n",
    "- `numpy.random.poisson(lam=1.0, size=None)` Draw samples from a Poisson distribution.\n",
    "\n",
    "表示对一个泊松分布进行采样，`size`表示采样的次数，`lam`表示一个单位内发生事件的平均值，函数的返回值表示一个单位内事件发生的次数。\n",
    "\n",
    "【例】假定某航空公司预定票处平均每小时接到42次订票电话，那么10分钟内恰好接到6次电话的概率是多少？\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "from scipy import stats\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "np.random.seed(20200605)\n",
    "lam = 42 / 6# 平均值：平均每十分钟接到42/6次订票电话\n",
    "size = 50000\n",
    "x = np.random.poisson(lam, size)\n",
    "'''或者\n",
    "#模拟服从泊松分布的50000个随机变量\n",
    "x = stats.poisson.rvs(lam,size=size)\n",
    "'''\n",
    "print(np.sum(x == 6) / size)  # 0.14988\n",
    "\n",
    "plt.hist(x)\n",
    "plt.xlabel('随机变量：每十分钟接到订票电话的次数')\n",
    "plt.ylabel('50000个样本中出现的次数')\n",
    "plt.show()\n",
    "#用poisson.pmf(k, mu)求对应分布的概率:概率质量函数 (PMF)\n",
    "x = stats.poisson.pmf(6, lam)\n",
    "print(x)  # 0.14900277967433773\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/2020111913161941.png?)\n",
    "\n",
    "\n",
    "### 超几何分布\n",
    "\n",
    "在超几何分布中，各次实验不是独立的，各次实验成功的概率也不等。\n",
    "超几何分布概率函数的数学表示：\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131647969.png#pic_center)\n",
    "\n",
    "\n",
    "- `numpy.random.hypergeometric(ngood, nbad, nsample, size=None)` Draw samples from a Hypergeometric distribution.\n",
    "\n",
    "表示对一个超几何分布进行采样，`size`表示采样的次数，`ngood`表示总体中具有成功标志的元素个数，`nbad`表示总体中不具有成功标志的元素个数，`ngood+nbad`表示总体样本容量，`nsample`表示抽取元素的次数（小于或等于总体样本容量），函数的返回值表示抽取`nsample`个元素中具有成功标识的元素个数。\n",
    "\n",
    "\n",
    "【例】一共20只动物里有7只是狗，抽取12只有3只狗的概率（无放回抽样）。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "from scipy import stats\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "np.random.seed(20200605)\n",
    "size = 500000\n",
    "x = np.random.hypergeometric(ngood=7, nbad=13, nsample=12, size=size)\n",
    "'''或者\n",
    "#用rvs(M, n, N, loc=0, size=1, random_state=None)模拟\n",
    "x = stats.hypergeom.rvs(M=20,n=7,N=12,size=size)\n",
    "'''\n",
    "print(np.sum(x == 3) / size)  # 0.198664\n",
    "\n",
    "plt.hist(x, bins=8)\n",
    "plt.xlabel('狗的数量')\n",
    "plt.ylabel('50000个样本中出现的次数')\n",
    "plt.title('超几何分布',fontsize=20)\n",
    "plt.show()\n",
    "\n",
    "\"\"\"\n",
    "M 为总体容量\n",
    "n 为总体中具有成功标志的元素的个数\n",
    "N,k 表示抽取N个元素有k个是成功元素\n",
    "\"\"\"\n",
    "x = range(8)\n",
    "#用hypergeom.pmf(k, M, n, N, loc)来计算k次成功的概率\n",
    "s = stats.hypergeom.pmf(k=x, M=20, n=7, N=12)\n",
    "print(np.round(s, 3))\n",
    "# [0.    0.004 0.048 0.199 0.358 0.286 0.095 0.01 ]\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131716148.png?)\n",
    "\n",
    "```\n",
    "'''\n",
    "超几何分布的均值与方差\n",
    "\n",
    "均值E(x) = N(n/M)\n",
    "方差Var(x) = N(n/M)(1-n/M)((M-N)/(M-1))\n",
    "注释：考虑n次实验的超几何分布，令p=n/M,当总体容量足够大时((M-N)/(M-1))近似于1，此时数学期望为Np，方差为Np(1-p).\n",
    "#用stats(M, n, N, loc=0, moments='mv')计算均值和方差\n",
    "stats.hypergeom.stats(20,7,12,moments='mv')\n",
    "'''\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## 连续型随机变量\n",
    "\n",
    "### 均匀分布\n",
    "\n",
    "- `numpy.random.uniform(low=0.0, high=1.0, size=None)` Draw samples from a uniform distribution.\n",
    "\n",
    "Samples are uniformly distributed over the half-open interval `[low, high)` (includes low, but excludes high).  In other words, any value within the given interval is equally likely to be drawn by `uniform`.\n",
    "\n",
    "【例】在low到high范围内，创建大小为size的均匀分布的随机数。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy import stats\n",
    "\n",
    "np.random.seed(20200614)\n",
    "a = 0\n",
    "b = 100\n",
    "size = 50000\n",
    "x = np.random.uniform(a, b, size=size)\n",
    "print(np.all(x >= 0))  # True\n",
    "print(np.all(x < 100))  # True\n",
    "y = (np.sum(x < 50) - np.sum(x < 10)) / size\n",
    "print(y)  # 0.40144\n",
    "\n",
    "plt.hist(x, bins=20)\n",
    "plt.show()\n",
    "\n",
    "a = stats.uniform.cdf(10, 0, 100)\n",
    "b = stats.uniform.cdf(50, 0, 100)\n",
    "print(b - a)  # 0.4\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131754948.png?)\n",
    "\n",
    "\n",
    "作为`uniform()`的特列，可以得到`[0,1)`之间的均匀分布的随机数。\n",
    "\n",
    "- `numpy.random.rand(d0, d1, ..., dn)`  Random values in a given shape.\n",
    "\n",
    "\n",
    "\n",
    "Create an array of the given shape and populate it with random samples from a uniform distribution over `[0, 1)`.\n",
    "\n",
    "\n",
    "\n",
    "【例】根据指定大小产生[0,1)之间均匀分布的随机数。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(20200614)\n",
    "print(np.random.rand())\n",
    "# 0.7594819171852776\n",
    "\n",
    "print(np.random.rand(5))\n",
    "# [0.75165827 0.16552651 0.0538581  0.46671446 0.89076925]\n",
    "\n",
    "print(np.random.rand(4, 3))\n",
    "# [[0.10073292 0.14624784 0.40273923]\n",
    "#  [0.21844459 0.22226682 0.37246217]\n",
    "#  [0.50334257 0.01714939 0.47780388]\n",
    "#  [0.08755349 0.86500477 0.70566398]]\n",
    "\n",
    "np.random.seed(20200614)\n",
    "print(np.random.uniform())  # 0.7594819171852776\n",
    "print(np.random.uniform(size=5))\n",
    "# [0.75165827 0.16552651 0.0538581  0.46671446 0.89076925]\n",
    "\n",
    "print(np.random.uniform(size=(4, 3)))\n",
    "# [[0.10073292 0.14624784 0.40273923]\n",
    "#  [0.21844459 0.22226682 0.37246217]\n",
    "#  [0.50334257 0.01714939 0.47780388]\n",
    "#  [0.08755349 0.86500477 0.70566398]]\n",
    "```\n",
    "\n",
    "作为`uniform`的另一特例，可以得到`[low,high)`之间均匀分布的随机整数。\n",
    "\n",
    "- `numpy.random.randint(low, high=None, size=None, dtype='l')` Return random integers from `low` (inclusive) to `high` (exclusive).\n",
    "\n",
    "Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).\n",
    "\n",
    "\n",
    "【例】若`high`不为`None`时，取[low,high)之间随机整数，否则取值[0,low)之间随机整数。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = np.random.randint(2, size=10)\n",
    "print(x)\n",
    "# [0 0 0 1 0 1 0 0 0 0]\n",
    "\n",
    "x = np.random.randint(1, size=10)\n",
    "print(x)\n",
    "# [0 0 0 0 0 0 0 0 0 0]\n",
    "\n",
    "x = np.random.randint(5, size=(2, 4))\n",
    "print(x)\n",
    "# [[3 3 0 1]\n",
    "#  [1 1 0 1]]\n",
    "\n",
    "x = np.random.randint(1, 10, [3, 4])\n",
    "print(x)\n",
    "# [[2 1 7 7]\n",
    "#  [7 2 4 6]\n",
    "#  [8 7 2 8]]\n",
    "```\n",
    "\n",
    "\n",
    "### 正态分布\n",
    "\n",
    "标准正态分布数学表示：\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131909797.png#pic_center)\n",
    "\n",
    "- `numpy.random.randn(d0, d1, ..., dn)` Return a sample (or samples) from the \"standard normal\" distribution.\n",
    "\n",
    "\n",
    "\n",
    "【例】根据指定大小产生满足标准正态分布的数组（均值为0，标准差为1）。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy import stats\n",
    "\n",
    "np.random.seed(20200614)\n",
    "size = 50000\n",
    "x = np.random.randn(size)\n",
    "y1 = (np.sum(x < 1) - np.sum(x < -1)) / size\n",
    "y2 = (np.sum(x < 2) - np.sum(x < -2)) / size\n",
    "y3 = (np.sum(x < 3) - np.sum(x < -3)) / size\n",
    "print(y1)  # 0.68596\n",
    "print(y2)  # 0.95456\n",
    "print(y3)  # 0.99744\n",
    "\n",
    "plt.hist(x, bins=20)\n",
    "plt.show()\n",
    "\n",
    "y1 = stats.norm.cdf(1) - stats.norm.cdf(-1)\n",
    "y2 = stats.norm.cdf(2) - stats.norm.cdf(-2)\n",
    "y3 = stats.norm.cdf(3) - stats.norm.cdf(-3)\n",
    "print(y1)  # 0.6826894921370859\n",
    "print(y2)  # 0.9544997361036416\n",
    "print(y3)  # 0.9973002039367398\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119131931877.png)\n",
    "\n",
    "\n",
    "还可以指定分布以及所需参数来进行随机，例如高斯分布中的mu和sigma。\n",
    "\n",
    "- `numpy.random.normal(loc=0.0, scale=1.0, size=None)` Draw random samples from a normal (Gaussian) distribution.\n",
    "\n",
    "`normal()`为创建均值为 loc（mu），标准差为 scale（sigma），大小为 size 的数组。\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119132016909.jpeg)\n",
    "\n",
    "```python\n",
    "sigma * np.random.randn(...) + mu\n",
    "```\n",
    "\n",
    "【例】\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = 0.5 * np.random.randn(2, 4) + 5\n",
    "'''或者\n",
    "#模拟10000个随机变量\n",
    "x = 0.5*stats.norm.rvs(size=(2,4))+5\n",
    "'''\n",
    "print(x)\n",
    "# [[5.39654234 5.4088702  5.49104652 4.95817289]\n",
    "#  [4.31977933 4.76502391 4.70720327 4.36239023]]\n",
    "\n",
    "np.random.seed(20200614)\n",
    "mu = 5#平均值\n",
    "sigma = 0.5#标准差\n",
    "x = np.random.normal(mu, sigma, (2, 4))\n",
    "print(x)\n",
    "# [[5.39654234 5.4088702  5.49104652 4.95817289]\n",
    "#  [4.31977933 4.76502391 4.70720327 4.36239023]]\n",
    "\n",
    "size = 50000\n",
    "x = np.random.normal(mu, sigma, size)\n",
    "\n",
    "print(np.mean(x))  # 4.996403463175092\n",
    "print(np.std(x, ddof=1))  # 0.4986846716715106（#样本标准差）\n",
    "'''\n",
    "ddof：int, optional\n",
    "Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.\n",
    "'''\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119132057585.png)\n",
    "\n",
    "```\n",
    "plt.hist(x, bins=20)\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119132129180.png)\n",
    "\n",
    "### 指数分布\n",
    "\n",
    "指数分布描述时间发生的时间长度间隔。\n",
    "\n",
    "指数分布的数学表示：\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119132204425.png#pic_center)\n",
    "\n",
    "- `numpy.random.exponential(scale=1.0, size=None)` Draw samples from an exponential distribution.\n",
    "\n",
    "【例】`scale = 1/lambda`\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy import stats\n",
    "\n",
    "np.random.seed(20200614)\n",
    "lam = 7\n",
    "size = 50000\n",
    "x = np.random.exponential(1 / lam, size)\n",
    "'''或者\n",
    "#rvs(loc=0, scale=1/lam, size=size, random_state=None)模拟\n",
    "'''\n",
    "y1 = (np.sum(x < 1 / 7)) / size\n",
    "y2 = (np.sum(x < 2 / 7)) / size\n",
    "y3 = (np.sum(x < 3 / 7)) / size\n",
    "print(y1)  # 0.63218\n",
    "print(y2)  # 0.86518\n",
    "print(y3)  # 0.95056\n",
    "\n",
    "plt.hist(x, bins=20)\n",
    "plt.show()\n",
    "\n",
    "y1 = stats.expon.cdf(1 / 7, scale=1 / lam)\n",
    "y2 = stats.expon.cdf(2 / 7, scale=1 / lam)\n",
    "y3 = stats.expon.cdf(3 / 7, scale=1 / lam)\n",
    "print(y1)  # 0.6321205588285577\n",
    "print(y2)  # 0.8646647167633873\n",
    "print(y3)  # 0.950212931632136\n",
    "```\n",
    "\n",
    "![在这里插入图片描述](https://img-blog.csdnimg.cn/20201119132227795.png)\n",
    "\n",
    "\n",
    "---\n",
    "\n",
    "## 其它随机函数\n",
    "\n",
    "### 随机从序列中获取元素\n",
    "\n",
    "- `numpy.random.choice(a, size=None, replace=True, p=None)` Generates a random sample from a given 1-D array.\n",
    "\n",
    "从序列中获取元素，若`a`为整数，元素取值从`np.range(a)`中随机获取；若`a`为数组，取值从`a`数组元素中随机获取。该函数还可以控制生成数组中的元素是否重复`replace`，以及选取元素的概率`p`。\n",
    "\n",
    "【例】\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = np.random.choice(10, 3)\n",
    "print(x)  # [2 0 1]\n",
    "\n",
    "x = np.random.choice(10, 3, p=[0.05, 0, 0.05, 0.9, 0, 0, 0, 0, 0, 0])\n",
    "print(x)  # [3 2 3]\n",
    "\n",
    "x = np.random.choice(10, 3, replace=False, p=[0.05, 0, 0.05, 0.9, 0, 0, 0, 0, 0, 0])\n",
    "print(x)  # [3 0 2]\n",
    "\n",
    "aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']\n",
    "x = np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])\n",
    "print(x) # ['pooh' 'rabbit' 'pooh' 'pooh' 'pooh']\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = np.random.randint(0, 10, 3)\n",
    "print(x)  # [2 0 1]\n",
    "```\n",
    "\n",
    "### 对数据集进行洗牌操作\n",
    "\n",
    "数据一般都是按照采集顺序排列的，但是在机器学习中很多算法都要求数据之间相互独立，所以需要先对数据集进行洗牌操作。\n",
    "\n",
    "- `numpy.random.shuffle(x)` Modify a sequence in-place by shuffling its contents.\n",
    "\n",
    "This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.\n",
    "\n",
    "对`x`进行重排序，如果`x`为多维数组，只沿第 0 轴洗牌，改变原来的数组，输出为None。\n",
    "\n",
    "【例】洗牌，改变自身内容，打乱顺序。\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = np.arange(10)\n",
    "np.random.shuffle(x)\n",
    "print(x)\n",
    "# [6 8 7 5 3 9 1 4 0 2]\n",
    "\n",
    "print(np.random.shuffle([1, 4, 9, 12, 15]))\n",
    "# None\n",
    "\n",
    "x = np.arange(20).reshape((5, 4))\n",
    "print(x)\n",
    "# [[ 0  1  2  3]\n",
    "#  [ 4  5  6  7]\n",
    "#  [ 8  9 10 11]\n",
    "#  [12 13 14 15]\n",
    "#  [16 17 18 19]]\n",
    "\n",
    "np.random.shuffle(x)\n",
    "print(x)\n",
    "# [[ 4  5  6  7]\n",
    "#  [ 0  1  2  3]\n",
    "#  [ 8  9 10 11]\n",
    "#  [16 17 18 19]\n",
    "#  [12 13 14 15]]\n",
    "```\n",
    "\n",
    "- `numpy.random.permutation(x)` Randomly permute a sequence, or return a permuted range.\n",
    "\n",
    "If `x` is a multi-dimensional array, it is only shuffled along its first index.\n",
    "            \n",
    "`permutation()`函数的作用与`shuffle()`函数相同，可以打乱第0轴的数据，但是它不会改变原来的数组。\n",
    "\n",
    "【例】\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(20200614)\n",
    "x = np.arange(10)\n",
    "y = np.random.permutation(x)\n",
    "print(y)\n",
    "# [6 8 7 5 3 9 1 4 0 2]\n",
    "\n",
    "print(np.random.permutation([1, 4, 9, 12, 15]))\n",
    "# [ 4  1  9 15 12]\n",
    "\n",
    "x = np.arange(20).reshape((5, 4))\n",
    "print(x)\n",
    "# [[ 0  1  2  3]\n",
    "#  [ 4  5  6  7]\n",
    "#  [ 8  9 10 11]\n",
    "#  [12 13 14 15]\n",
    "#  [16 17 18 19]]\n",
    "\n",
    "y = np.random.permutation(x)\n",
    "print(y)\n",
    "# [[ 8  9 10 11]\n",
    "#  [ 0  1  2  3]\n",
    "#  [12 13 14 15]\n",
    "#  [16 17 18 19]\n",
    "#  [ 4  5  6  7]]\n",
    "```\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "---\n",
    "\n",
    "**参考文献**\n",
    "\n",
    "- https://www.jianshu.com/p/63434ad5ea64"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python35",
   "language": "python",
   "name": "python35"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "165px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
